﻿using ECLogger;
using ECMessageQueue;
using FESSC_MESSAGE;
using System.Threading;

namespace FESSC_WORKBENCH
{
    public class MQWorker
    {
        public MQClient mqclient;
        public Logger log;
        public Thread tMessageLoop;
        private OperationDict opDict;
        private bool isRunning = true;

        public MQWorker(string serverip, OperationDict opdict, Logger logger)
        {
            log = logger;
            opDict = opdict;
            mqclient = new MQClient(serverip, log);
        }

        public void getMessageLoop()
        {
            while (isRunning)
            {
                var mqmsg = mqclient.getMessage();
                log.Debug("Recive message from server:\r\n{1}",
                    mqmsg.remote, mqmsg.content);
                Msg msg = new Msg(mqmsg.content);
                string msgroot = msg.getRootName();
                switch (msgroot)
                {
                    case "rq":
                        break;
                    case "rs":
                        string operation = msg.getValueByXpath("/rs/header/operation");
                        try
                        {
                            opDict.rsOps[operation](mqmsg);
                        }
                        catch(System.Exception)
                        {
                            log.Error("Undefind process function for {0}.", operation);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        public void startMessageLoop()
        {
            tMessageLoop = new Thread(new ThreadStart(getMessageLoop));
            tMessageLoop.Start();
        }

        public void stopMessageLoop()
        {
            tMessageLoop.Abort();
        }

        public void close()
        {
            isRunning = false;
            stopMessageLoop();
            mqclient.close();
        }
    }
}
